<?php
require_once ROOT_PATH . 'source/include/cls_tree.php';
/**
 * 地址类
 */
class Area {

	/**
	 * 防止克隆
	 *
	 */
	private function __clone() {}

	/**
	 * Singleton instance
	 *
	 * @return Object
	 */
	public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset) {
		if (self::$_instance === null) {
			self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
		}
		return self::$_instance;
	}

	public function __construct() {
		global $Db;
		$this->db = $GLOBALS['Db'];
		$this->cache = new Cache();
		$this->tdata = new InitTree();
		$areas = $this->cache->get('oa_area_full');
		if (!$areas) {
			$areas = Common::array_re_index($this->db->query('select  areacode as id,areaname as name,uppk as parentid from ' . $GLOBALS['Base']->table('area'), 'All'), 'id');
			$this->cache->put('oa_area_full', $areas);
		}
		$this->tdata->set_tree($areas);
	}
	/**
	 * 获取某省列表,$pid 为空,则获取所有
	 *  @param $pid
	 **/
	public function province() {
		$data = $this->cache->get('oa_area_province');
		if (!$data) {
			$tmp = $this->tdata->get_child('100000');
			foreach ($tmp as $k => $v) {
				$data[$k] = $v['name'];
			}
			$this->cache->put('oa_area_province', $data);

		}
		return $data;
	}

	/**
	 * 获取某省下的城市
	 *  @param $pid
	 **/
	public function city($pid) {
		if (!$pid) {
			return false;
		}

		$tmp = $this->tdata->get_child($pid);
		foreach ($tmp as $k => $v) {
			$ls[$k] = $v['name'];
		}
		return $ls;
	}

	/**
	 * 获取指定城市县区
	 * @param $aid
	 */
	public function zone($pid) {
		if (!$pid) {
			return false;
		}

		$tmp = $this->tdata->get_child($pid);
		foreach ($tmp as $k => $v) {
			$ls[$k] = $v['name'];
		}
		return $ls;

	}

	function getProvince() {
		$provicelist = S('provicelist');
		if (empty($provicelist)) {

			$provicelist = $this->db->query('select * from ' . $GLOBALS['Base']->table('area') . ' where level=\'省\'  ', 'All');
			S('provicelist', $provicelist, 360000);
		}
		return $provicelist;
	}

	function getCity() {
		$citylist = S('citylist');
		if (empty($citylist)) {
			$citylist = $this->db->query('select * from ' . $GLOBALS['Base']->table('area') . ' where level=\'市\'  ', 'All');
		}
		return $citylist;
	}

	function getCounty() {
		$countylist = S('countylist');
		if (emptSy($citylist)) {
			$where["level"] = "区";
			$countylist = $this->db->query('select * from ' . $GLOBALS['Base']->table('area') . ' where level=\'区\'  ', 'All');
		}
		return $countylist;
	}

}
?>